package cn.well.cloud.base.wechat.api.impl;

import cn.hutool.core.util.StrUtil;
import cn.well.cloud.base.util.HttpUtils;
import cn.well.cloud.base.wechat.api.AppWXUserAPI;
import cn.well.cloud.base.wechat.model.WXUser;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class AppWXUser  implements AppWXUserAPI {


    @Override
    public WXUser getUserInfo(String authorizerAccessToken, String openId) {
        // 访问微信服务器
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+ authorizerAccessToken+"&openid="+openId + "&lang=zh_CN";
        try {
            String result = HttpUtils.doGet(url);
            JSONObject json = JSONObject.parseObject(result);
            if (json != null&&json.containsKey("errcode")) {
                log.info("获取用户信息错误："+result);
                return null;
            }else {
                WXUser wxUser = JSONObject.toJavaObject(json, WXUser.class);
                return wxUser;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Object getUserInfoList(String authorizerAccessToken,String nextOpenId) {
        // 访问微信服务器
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+ authorizerAccessToken;
        if(StrUtil.isNotEmpty(nextOpenId)){
            url = url+"&next_openid="+nextOpenId ;
        }
        try {
            String result = HttpUtils.doGet(url);
            JSONObject json = JSONObject.parseObject(result);
            if (json != null&&json.containsKey("errcode")) {
                log.info("批量获取用户信息错误："+result);
                return null;
            }else {
                return json;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
